import { ElMessage } from 'element-plus/es'
import { Encrypt } from '@/utils/bcryptUtil'
import api from '@/api/api'
import { useUserStore } from '@/stores/user'
import router from '@/router'
import config from '@/config/config'
import { useCommonStore } from '@/stores/common'
import { ArticlePath } from '@/models/@types'

class UserService {
  public login(username: any, password: any): Promise<void> {
    const userStore = useUserStore()
    let params = new URLSearchParams()
    params.append('username', username)
    params.append('password', Encrypt(password))
    return new Promise((resolve) => {
      return api.login(params).then(({ data }) => {
        if (data.flag) {
          userStore.userInfo = data.data
          sessionStorage.setItem('token', data.data.token)
          userStore.token = data.data.token
          ElMessage({ message: '登录成功', type: 'success' })
          resolve()
        } else {
          ElMessage({ message: data.message, type: 'error' })
        }
      })
    })
  }

  public loginOut() {
    const userStore = useUserStore()
    api.logout().then(({ data }) => {
      if (data.flag) {
        userStore.userInfo = ''
        userStore.token = ''
        userStore.accessArticles = []
        sessionStorage.removeItem('token')
        ElMessage({ message: '登出成功', type: 'success' })
      } else {
        ElMessage({ message: data.message, type: 'error' })
      }
    })
  }

  public register(username: any, password: any, nickName: any, code: any): Promise<void> {
    let params = {
      code: code,
      username: username,
      password: password,
      nickName: nickName
    }
    return new Promise((resolve) => {
      return api.register(params).then(async ({ data }) => {
        if (data.flag) {
          ElMessage({ message: '注册成功', type: 'success' })
          await this.login(username, password).then(()=>console.log('注册后自动登录'))
          location.reload()
          resolve()
        } else {
          ElMessage({ message: data.message, type: 'error' })
        }
      })
    })
  }

  public updatePassword(loginInfo: any): Promise<void> {
    return new Promise((resolve) => {
      return api.updatePassword(loginInfo).then(({ data }) => {
        if (data.flag) {
          ElMessage({ message: '修改成功', type: 'success' })
          resolve()
        } else {
          ElMessage({ message: data.message, type: 'error' })
        }
      })
    })
  }

  public accessArticle(articleId: any, articlePassword: any): Promise<void> {
    const userStore = useUserStore()
    return new Promise((resolve) => {
      api.accessArticle({ articleId: articleId, articlePassword: articlePassword })
        .then(({ data }) => {
          if (data.flag) {
            userStore.accessArticles.push(articleId)
            router.push({ path: ArticlePath.Path + articleId }).then(() => resolve())
          } else {
            ElMessage({ message: data.message, type: 'error' })
          }
        })
    })
  }

  public QQLoginMethod() {
    const commonStore = useCommonStore()
    if (commonStore.isMobile) {
      //@ts-ignore
      QC.Login.showPopup({
        appId: config.qqLogin.QQ_APP_ID,
        redirectURI: config.qqLogin.QQ_REDIRECT_URI
      })
    } else {
      window.open(
        'https://graph.qq.com/oauth2.0/show?which=Login&display=pc&client_id=' +
        +config.qqLogin.QQ_APP_ID +
        '&response_type=token&scope=all&redirect_uri=' +
        config.qqLogin.QQ_REDIRECT_URI,
        '_self'
      )
    }
  }
}

export const userService: UserService = new UserService()
